<template>
  <div>
    <!-- 卡片区 -->
    <el-card style="margin-bottom: 100px">
      <!-- 表格上部搜索，新增仓库区 -->
      <el-row :gutter="20" type="flex" justify="space-between">
        <el-col :span="6">
          <el-input
            placeholder="搜索仓库名称、组织架构"
            v-model="searchStr"
            clearable
            @clear="clearSearchStr"
          ></el-input>
        </el-col>

        <el-col>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="search(searchStr, 1)"
            >搜索仓库</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addDialogVisible = true"
            >新增仓库</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="customerList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="gitlab_name" label="仓库名"></el-table-column>
        <el-table-column prop="branch_name" label="所属部门"></el-table-column>
        <el-table-column prop="group_name" label="所属小组"></el-table-column>

        <el-table-column
          prop="gitlab_clone_url"
          label="仓库路径"
        ></el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column
          prop="update_time"
          label="上一次更新时间"
        ></el-table-column>

        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="openEditDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteById(scope.row.rid)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <div class="block">
        <el-pagination
          layout="prev, pager, next, jumper, total"
          :total="customernum"
          :current-page.sync="pagenum"
          @current-change="getCustomerList"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 新增仓库的弹出对话框 -->
    <el-dialog
      title="新增仓库"
      :visible.sync="addDialogVisible"
      width="40%"
      @close="addFormClose()"
    >
      <!-- 主体区 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="所属部门" prop="branchId">
          <el-select
            v-model="addForm.branchId"
            placeholder="请选择"
            @focus="queryBranchList"
            @change="changeSelectBranch"
          >
            <el-option
              v-for="item in branchArr"
              :key="item.id"
              :label="item.branch_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属小组" prop="groupId">
          <el-select
            v-model="addForm.groupId"
            placeholder="请选择"
            @focus="querySearchAsync(addForm.branchId)"
          >
            <el-option
              v-for="item in groupIdArr"
              :key="item.groupId"
              :label="item.group_name"
              :value="item.groupId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名" prop="gitlabName">
          <el-input v-model="addForm.gitlabName"></el-input>
        </el-form-item>
        <el-form-item label="仓库地址" prop="gitlabCloneUrl">
          <el-input v-model="addForm.gitlabCloneUrl"></el-input>
        </el-form-item>
        <div style="color: red; margin-left: 100px">
          仓库地址应以/开头 ，例如"/URD/fe/wenda-pc"
        </div>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addCustomer()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户的弹出对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="40%"
      @open="queryBranchGroupList"
    >
      <!-- 主体区 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="所属部门" prop="branchId">
          <el-select
            v-model="editForm.branchId"
            placeholder="请选择"
            @change="changeSelectBranch"
          >
            <el-option
              v-for="item in branchArr"
              :key="item.id"
              :label="item.branch_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属小组" prop="groupId">
          <el-select
            v-model="editForm.groupId"
            placeholder="请选择"
            @focus="querySearchAsync(editForm.branchId)"
          >
            <el-option
              v-for="item in groupIdArr"
              :key="item.groupId"
              :label="item.group_name"
              :value="item.groupId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="仓库名" prop="gitlabName">
          <el-input v-model="editForm.gitlabName"></el-input>
        </el-form-item>
        <el-form-item label="仓库地址" prop="gitlabCloneUrl">
          <el-input v-model="editForm.gitlabCloneUrl"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer 1111">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editCustomer()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchReposApi,
  getAllReposApi,
  addNewReposApi,
  deleteReposApi,
  getBranchList,
  getGroupListByBranchId,
} from '@/api/repos';
export default {
  created() {
    this.getCustomerList(1);
  },
  data() {
    let gitlabCloneUrlValidator = (rule, value, callback) => {
      if (!/^\//.test(value)) {
        callback(new Error('格式错误，示例格式：/URD/fe/wenda-pc'));
      } else {
        callback();
      }
    };
    return {
      searchStr: '',
      customerList: [],
      //当前所在页码
      pagenum: 1,
      //数据总条数
      customernum: 0,
      //控制用户添加对话框的可见与否
      addDialogVisible: false,
      //添加新用户表单
      addForm: {
        branchId: '',
        groupId: '',
        gitlabId: '',
        gitlabName: '',
        gitlabCloneUrl: '',
      },
      //添加新用户的表单规则
      addFormRules: {
        branchId: [
          {
            required: true,
            message: '请选择部门',
            trigger: 'blur',
          },
        ],
        groupId: [
          {
            required: true,
            message: '请选择小组',
            trigger: 'blur',
          },
        ],
        gitlabName: [
          {
            required: true,
            message: '请输入仓库名',
            trigger: 'blur',
          },
        ],
        gitlabCloneUrl: [
          {
            required: true,
            validator: gitlabCloneUrlValidator,
            trigger: 'blur',
          },
        ],
      },
      // 设计的时候考虑编辑和新增使用两个不同的表单
      //编辑用户弹出框的可见与否
      editDialogVisible: false,
      //编辑表单
      editForm: {
        rid: null,
        branchId: '',
        groupId: '',
        gitlabId: '',
        gitlabName: '',
        gitlabCloneUrl: '',
      },
      //编辑用户的表单规则和新增的表单规则相同
      editFormRules: {
        rid: [
          {
            required: true,
            message: '请输入rid',
            trigger: 'blur',
          },
        ],
        gitlabId: [
          {
            required: true,
            message: '请输入仓库ID',
            trigger: 'blur',
          },
        ],
        gitlabName: [
          {
            required: true,
            message: '请输入仓库名',
            trigger: 'blur',
          },
        ],
        gitlabCloneUrl: [
          {
            required: true,
            message: '请输入仓库地址',
            trigger: 'blur',
          },
        ],
      },
      groupIdArr: [],
      branchArr: [],
    };
  },
  methods: {
    //请求表格数据
    getCustomerList(pagenum) {
      if (this.searchStr === '') {
        getAllReposApi({
          pageNum: pagenum || this.pagenum,
          pageSize: 10,
        }).then((res) => {
          if (res?.reposList && Array.isArray(res?.reposList)) {
            this.customerList = res?.reposList;
            this.customernum = res?.total; // 因为不知道总数(接口没返回)
          } else {
            this.$message.error('数据异常!');
          }
        });
      } else {
        this.search(this.searchStr, pagenum);
      }
    },
    //搜素部门列表
    queryBranchList() {
      getBranchList().then((res) => {
        console.log('queryBranchList -->', res);
        const { teams } = res;
        this.branchArr = teams;
      });
    },
    async queryBranchGroupList() {
      await this.queryBranchList();
      await getGroupListByBranchId(this.editForm.branchId).then((res) => {
        this.groupIdArr = res['teams'];
      });
    },
    changeSelectBranch() {
      this.groupIdArr = [];
      this.addForm.groupId = null;
      this.editForm.groupId = null;
    },
    // 新增表单中搜索组列表
    querySearchAsync(branchId) {
      console.log('querySearchAsync --> ', this.addForm.branchId);
      if (!branchId) {
        this.groupIdArr = [];
        return;
      }
      getGroupListByBranchId(branchId).then((res) => {
        this.groupIdArr = res['teams'];
      });
    },
    //搜索
    search(searchStr, pageNum) {
      if (searchStr.trim() === '') {
        this.$message({
          type: 'error',
          message: '请输入有效内容',
        });
        return;
      }
      this.pagenum = pageNum;
      searchReposApi({ pageSize: 10, pageNum, searchStr: searchStr }).then(
        (res) => {
          if (res?.reposList && Array.isArray(res?.reposList)) {
            this.customerList = res?.reposList;
            this.customernum = res?.total;
          } else {
            this.this.$message.error('数据异常!');
          }
        }
      );
    },
    clearSearchStr() {
      this.getCustomerList(1);
    },
    //新增仓库
    addCustomer() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) {
          this.$message.error('表单校验失败!');
          //格式验证不对，res为flase
          return;
        }
        addNewReposApi({
          groupId: +this.addForm.groupId,
          gitlabName: this.addForm.gitlabName,
          gitlabCloneUrl: this.addForm.gitlabCloneUrl,
        }).then((res) => {
          if (!res) {
            this.$message.success('新增成功');
            this.getCustomerList(1);
            this.addDialogVisible = false;
            this.addForm = {
              rid: null,
              groupId: '',
              gitlabId: '',
              gitlabName: '',
              gitlabCloneUrl: '',
            }; // 新增成功清下表单状态
            return;
          }
          this.$message.error('服务异常，新增失败，请重试！');
        });
      });
    },
    //关闭对话框（即可见性为false）触发，清空填入数据
    addFormClose() {
      this.$refs.addFormRef.resetFields();
    },
    //删除数据
    deleteById(rid) {
      deleteReposApi({
        rid,
      }).then((res) => {
        if (!res) {
          this.getCustomerList(1);
          return this.$message.success('删除成功');
        }
        this.$message.error('服务异常，删除失败，请重试！');
      });
    },
    //打开编辑数据对话框,把要编辑用户的数据带进去
    openEditDialog(from) {
      this.editDialogVisible = true;
      console.log('openEditDialog --> ', from);
      this.editForm = {
        rid: from?.rid,
        branchId: from?.branch_id,
        groupId: from?.group_id,
        gitlabName: from?.gitlab_name,
        gitlabCloneUrl: from?.gitlab_clone_url,
      };
    },
    //编辑对话框的确定按钮触发保存
    editCustomer() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) {
          //格式验证不对，res为flase
          return;
        }
        console.log('用户编辑表单验证成功');
        addNewReposApi({
          rid: +this.editForm.rid,
          branchId: this.editForm.branch_id,
          groupId: +this.editForm.groupId,
          gitlabName: this.editForm.gitlabName,
          gitlabCloneUrl: this.editForm.gitlabCloneUrl,
        }).then((res) => {
          if (!res) {
            this.$message.success('修改成功');
            this.getCustomerList(1);
            this.editDialogVisible = false;
            this.editForm = {
              rid: null,
              groupId: '',
              gitlabId: '',
              gitlabName: '',
              gitlabCloneUrl: '',
            }; // 新增成功清下表单状态
            return;
          }
          this.$message.error('服务异常，修改失败，请重试！');
        });
      });
    },
  },
};
</script>

<style lang="less" scoped></style>
